package com.hsj.goldstore.base;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.WindowManager;

import com.hsj.goldstore.utils.ActivityCollector;
import com.hsj.goldstore.utils.Helper;

import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/3/21.
 */

public abstract class BaseMvpActivity<P extends IPresenter<V>, V extends BaseMvpView> extends AppCompatActivity implements BaseMvpView, LoaderManager.LoaderCallbacks<P> {

    private static final int BASE_LOAD_CODE = 1000;
    protected P presenter;
    private boolean isFirst = true;
    protected ProgressDialog progressDialog;
    public static final String DATA_BUNDLE = "bundle";

    /**
     * @return 获取布局contentView
     */
    protected abstract int getResouseId();

    /**
     * 资源初始化，和事件绑定
     */
    protected abstract void initView();

    /**
     * 数据初始化
     */
    protected abstract void initData();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //隐藏软键盘
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        super.onCreate(savedInstanceState);
        setContentView(getResouseId());
        ButterKnife.bind(this);
        //初始化loader
        getSupportLoaderManager().initLoader(BASE_LOAD_CODE, null, this);
        ActivityCollector.addActivity(this);
        progressDialog = new ProgressDialog(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //view 与presenter绑定
        presenter.attachView((V) this);
        if (isFirst) {
            initView();
            initData();
            isFirst = false;
        }
    }


    @Override
    public void onLoadFinished(Loader<P> loader, P data) {
        presenter = data;
    }

    @Override
    public void onLoaderReset(Loader<P> loader) {
        presenter = null;
    }

    @Override
    public void showError(String err) {
        Helper.showToast(this, err);
    }

    @Override
    public void showProgress(String msg) {
        if (null == progressDialog) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setCancelable(true);
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    @Override
    public void hideProgress() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }


    public static void getIntantce(Context context, Class cls) {
        getIntantce(context, cls, null);
    }

    public static void getIntantce(Context context, Class cls, Bundle bundle) {
        Intent intent = new Intent(context, cls);
        intent.putExtra(DATA_BUNDLE, bundle);
        context.startActivity(intent);
    }

    /**
     * @param permissions 子类要申请的权限
     * @return 6.0 有权限检查
     */
    public boolean hasPermission(String... permissions) {
        //6.0以下不用权限检查
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param code        子类申请权限请求码
     * @param permissions 子类要申请的权限
     * @param msg         提示用户为什么要申请该权限
     *                    申请权限
     */
    public void requestPerssion(final int code, String msg, final String... permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                new AlertDialog.Builder(this)
                        .setMessage(TextUtils.isEmpty(msg) ? "" : msg)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //申请权限
                                ActivityCompat.requestPermissions(BaseMvpActivity.this, permissions, code);
                            }
                        })
                        .show();
            } else {
                ActivityCompat.requestPermissions(this, permissions, code);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults[0] != PackageManager.PERMISSION_DENIED) {
                    Helper.showToast(BaseMvpActivity.this, "请开启拨打电话权限");
                } else {
                    callPhone();
                }
                break;
        }
    }

    public void callPhone() {
    }

    @Override
    protected void onDestroy() {
        presenter.dettachView();
        super.onDestroy();
        ActivityCollector.removeActiivity(this);
    }
}
